// ActivityManagementFragment.java
package com.xxxy.ljh.myapplication.activity.Fragment;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.xxxy.ljh.myapplication.Adapter.ActivityAdapter;
import com.xxxy.ljh.myapplication.Dao.ActivityDao;
import com.xxxy.ljh.myapplication.DaoImpl.ActivityDaoImpl;
import com.xxxy.ljh.myapplication.R;
import com.xxxy.ljh.myapplication.model.ActivityItem;
import java.util.ArrayList;
import java.util.List;

/**
 * 活动管理界面 Fragment 类
 * <p>
 * 负责展示、新增和管理活动信息。提供用户交互界面以录入新的活动，并显示已有活动列表。
 * 使用 RecyclerView 展示活动项，通过 ActivityAdapter 进行适配。
 * </p>
 */
public class ActivityManagementFragment extends Fragment {

    private RecyclerView recyclerViewActivities;
    private ActivityAdapter activityAdapter;
    private List<ActivityItem> activityList;
    private EditText etActivityName, etActivityDescription, etActivityTime;
    private Button btnAddActivity;
    private EditText etActivityLocation, etPointsRule, etMaxParticipants;
    private Spinner spinnerActivityType;

    /**
     * 创建 Fragment 的视图层次结构
     *
     * @param inflater           用于将 XML 布局文件转换为 View 对象的 LayoutInflater
     * @param container          可能包含 Fragment 的父 ViewGroup（可为空）
     * @param savedInstanceState 包含之前保存的状态数据（如果存在），否则为 null
     * @return 返回该 Fragment 的根视图 View
     */
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_activity_management, container, false);

        initViews(view);
        setupRecyclerView();
        setupEventListeners();

        loadActivities(); // 加载活动数据

        return view;
    }

    /**
     * 当 Fragment 变得可见时调用此方法，用于刷新活动数据
     */
    @Override
    public void onResume() {
        super.onResume();
        loadActivities(); // 每次页面可见时刷新数据
    }

    /**
     * 初始化布局中的各个控件组件
     *
     * @param view 当前 Fragment 的根视图
     */
    private void initViews(View view) {
        recyclerViewActivities = view.findViewById(R.id.recyclerViewActivities);
        etActivityName = view.findViewById(R.id.etActivityName);
        etActivityDescription = view.findViewById(R.id.etActivityDescription);
        etActivityTime = view.findViewById(R.id.etActivityTime);
        etActivityLocation = view.findViewById(R.id.etActivityLocation);
        etPointsRule = view.findViewById(R.id.etPointsRule);
        etMaxParticipants = view.findViewById(R.id.etMaxParticipants);
        spinnerActivityType = view.findViewById(R.id.spinnerActivityType);
        btnAddActivity = view.findViewById(R.id.btnAddActivity);

        activityList = new ArrayList<>();

        // 设置活动类型选项
        String[] activityTypes = {"常规活动", "社团活动", "公益活动", "讲座活动"};
        ArrayAdapter<String> adapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_item, activityTypes);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerActivityType.setAdapter(adapter);
    }

    /**
     * 配置 RecyclerView 并绑定 Adapter 和 LayoutManager
     */
    private void setupRecyclerView() {
        // 传入 getContext() 作为 Context 参数
        activityAdapter = new ActivityAdapter(getContext(), activityList);
        recyclerViewActivities.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerViewActivities.setAdapter(activityAdapter);
    }

    /**
     * 绑定按钮点击事件监听器
     */
    private void setupEventListeners() {
        btnAddActivity.setOnClickListener(v -> addNewActivity());
    }

    /**
     * 添加一个新的活动条目到数据库及 UI 列表中
     * <p>
     * 收集界面上输入的信息，验证后创建 ActivityItem 实体对象，
     * 插入数据库并更新本地列表与 RecyclerView 显示。
     * </p>
     */
    private void addNewActivity() {
        String name = etActivityName.getText().toString().trim();
        String description = etActivityDescription.getText().toString().trim();
        String time = etActivityTime.getText().toString().trim();
        String location = etActivityLocation.getText().toString().trim();
        String pointsRuleStr = etPointsRule.getText().toString().trim();
        String maxParticipantsStr = etMaxParticipants.getText().toString().trim();
        String activityType = spinnerActivityType.getSelectedItem().toString();

        if (name.isEmpty() || description.isEmpty() || time.isEmpty() ||
                location.isEmpty() || pointsRuleStr.isEmpty() || maxParticipantsStr.isEmpty()) {
            Toast.makeText(getContext(), "请填写完整信息", Toast.LENGTH_SHORT).show();
            return;
        }

        int pointsRule, maxParticipants;
        try {
            pointsRule = Integer.parseInt(pointsRuleStr);
            maxParticipants = Integer.parseInt(maxParticipantsStr);
        } catch (NumberFormatException e) {
            Toast.makeText(getContext(), "积分规则和最大参与人数必须是数字", Toast.LENGTH_SHORT).show();
            return;
        }

        // 创建新活动对象
        ActivityItem newActivity = new ActivityItem();
        newActivity.setTitle(name);
        newActivity.setDescription(description);
        newActivity.setStartTime(time);
        newActivity.setEndTime(time);
        newActivity.setLocation(location);
        newActivity.setPointsRule(pointsRule);
        newActivity.setMaxParticipants(maxParticipants);
        newActivity.setActivityType(activityType);

        // 设置默认值
        newActivity.setAssociationId(1); // 默认社团ID，实际应根据当前用户所属社团设置
        newActivity.setOrganizerId(1); // 默认组织者ID，实际应根据当前用户ID设置
        newActivity.setSignupDeadline(time);
        newActivity.setCost(0.0);
        newActivity.setStatus(1); // 1表示活动有效

        // 保存到数据库
        ActivityDao activityDao = new ActivityDaoImpl(getContext());
        long result = activityDao.createActivity(newActivity);

        if (result > 0) {
            // 设置数据库生成的ID
            newActivity.setId((int) result);

            // 添加到列表并更新UI
            activityList.add(newActivity);
            activityAdapter.notifyItemInserted(activityList.size() - 1);

            // 清空输入框
            etActivityName.setText("");
            etActivityDescription.setText("");
            etActivityTime.setText("");
            etActivityLocation.setText("");
            etPointsRule.setText("");
            etMaxParticipants.setText("");
            spinnerActivityType.setSelection(0); // 重置为第一个选项

            Toast.makeText(getContext(), "活动添加成功", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(getContext(), "活动添加失败", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 从数据库加载所有活动数据并更新 RecyclerView 显示
     */
    private void loadActivities() {
        // 从数据库加载活动数据
        try {
            ActivityDao activityDao = new ActivityDaoImpl(getContext());
            activityList.clear();
            // 获取所有活动或者根据特定条件获取活动
            List<ActivityItem> dbActivities = activityDao.getAllActivities();
            activityList.addAll(dbActivities);
            activityAdapter.notifyDataSetChanged();
        } catch (Exception e) {
            Toast.makeText(getContext(), "加载活动数据失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }
}
